<template>
  <div>
    <div class="header">
      <h6>员工管理</h6>
      <el-button type="primary" round @click="dialogVisible1 = true"
        >+ 新增员工
      </el-button>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      :header-row-style="
        () => {
          return 'line-height:50px';
        }
      "
    >
      <el-table-column prop="id" label="序号" width="180px"></el-table-column>
      <el-table-column prop="name" label="姓名" width="180px">
      </el-table-column>
      <el-table-column label="头像" width="180px">
        <template v-slot="scope">
          <!--          {{ scope.row.image}}-->
          <img :src="scope.row.image" alt="img" width="50px" />
        </template>
      </el-table-column>
      <el-table-column label="性别" width="180px">
        <template v-slot="scope">
          {{ scope.row.gender === 1 ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column label="部门" width="180px">
        <template v-slot="scope">
          {{ scope.row.dept == null ? "" : scope.row.dept.name }}
        </template>
      </el-table-column>
      <el-table-column label="入职时间" width="180px" center>
        <template v-slot="scope">
          {{ $moment(scope.row.createTime).format("L") }}
        </template>
      </el-table-column>
      <el-table-column label="更改时间" width="180px">
        <template v-slot="scope">
          {{ $moment(scope.row.updateTime).format("L") }}
        </template>
      </el-table-column>

      <el-table-column align="right">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      title="编辑部门"
      :visible.sync="dialogVisible"
      width="30%"
      center
    >
      <span>
        <el-form label-width="80px" :model="formLabelAlign">
          <el-form-item label="部门名称">
            <el-input v-model="formLabelAlign.name"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateDept">保存</el-button>
      </span>
    </el-dialog>

    <el-dialog title="新增员工" :visible.sync="dialogVisible1" width="50%">
      <span>
        <el-form label-width="80px" :model="formLabelAlign">
          <el-form-item label="员工名称">
            <el-input v-model="formLabelAlign.username"></el-input>
          </el-form-item>
          <el-form-item label="员工姓名">
            <el-input v-model="formLabelAlign.name"></el-input>
          </el-form-item>
          <el-form-item label="员工性别">
            <el-select v-model="formLabelAlign.gender" placeholder="请选择">
              <el-option label="男" value="0"></el-option>
              <el-option label="女" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="图片">
            <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="部门">
            <el-select
              v-model="formLabelAlign.deptId"
              placeholder="请选择"
              @focus="getOptions"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="入职时间">
            <el-input v-model="formLabelAlign.entrydate"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取消</el-button>
        <el-button type="primary" @click="addEmp">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      tableData: [],
      dialogVisible: false,
      dialogVisible1: false,
      formLabelAlign: {},
      row: {},
      currentPage: 1,
      total: 0,
      pageSize: 0,
      chagecurrentPage: "",
      chagepageSize: "",
      options: [],
      value: "",
      imageUrl: "",
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    getOptions(e) {
      console.log(e);
      request
        .get(
          `emp/emps?currentPage=${this.chagecurrentPage}&pageSize=${this.chagepageSize}`
        )
        .then((data) => {
          console.log("this is data", data.data.data.list);

          let lists = data.data.data.list;
          lists.forEach((item) => {
            this.options.push(item.dept);
          });

          console.log("dept", this.options);
          //this.options = ;
        })
        .catch((error) => {
          console.error(error);
        });
    },
    handleEdit(index, row) {
      this.dialogVisible = true;
      this.row = row;
    },
    handleDelete(index, row) {
      console.log(index, row.id);
      let ids = [];
      ids.push(row.id);
      console.log("ids", ids);

      this.$confirm("永久删除该员工, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          console.log("删除成功", this);
          request
            .delete(`dept/delete?ids=${ids}`)
            .then((data) => {
              console.log(data);
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getData();
            })
            .catch((error) => {
              console.error(error);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    updateDept() {
      this.dialogVisible = false;
      console.log(this.row.id);
      console.log(this.formLabelAlign.name);
      request
        .put("dept/update", {
          id: this.row.id,
          name: this.formLabelAlign.name,
        })
        .then((data) => {
          console.log(data.data);
          this.$message({
            message: "恭喜你，更新成功",
            type: "success",
          });
          //this.formLabelAlign.name = "";
          this.getData();
        })
        .catch((error) => {
          console.error(error);
          this.$message.error("更新失败");
        });
    },
    getData() {
      request
        .get(
          `emp/emps?currentPage=${this.chagecurrentPage}&pageSize=${this.chagepageSize}`
        )
        .then((data) => {
          console.log("this is data", data.data.data);
          this.tableData = data.data.data.list;
          this.total = data.data.data.total;
          this.pageSize = data.data.data.pageSize;
        })
        .catch((error) => {
          console.error(error);
        });
    },
    addEmp() {
      this.dialogVisible1 = false;
      this.formLabelAlign.image = this.imageUrl;
      console.log("val", this.value);

      console.log("this.formLabelAlign", this.formLabelAlign.deptId);
      request
        .post("emp/add", {
          username: this.formLabelAlign.username,
          name: this.formLabelAlign.name,
          gender: this.formLabelAlign.gender,
          image: this.formLabelAlign.image,
          deptId: this.formLabelAlign.deptId,
        })
        .then((data) => {
          console.log(data);
          this.$notify({
            title: "成功",
            message: "添加成功",
            type: "success",
          });
          this.getData();
          //this.formLabelAlign.name = "";
        })
        .catch((error) => {
          console.error(error);
          this.$notify.error({
            title: "错误",
            message: "添加失败",
          });
        });
    },
    handleSizeChange(pageSize) {
      console.log(`每页 ${pageSize} 条`);
      this.chagepageSize = pageSize;
      this.getData();
    },
    handleCurrentChange(currentPage) {
      console.log(`当前页: ${currentPage}`);
      this.chagecurrentPage = currentPage;
      this.getData();
    },
  },
  mounted() {
    // console.log('axios', this.axios);
    // console.log('moment', this.$moment);
    this.getData();
  },
};
</script>

<style scoped>
.block {
  float: right;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}

.header {
  height: 200px;
  float: left;
  margin-bottom: 0;
}

.header h6 {
  height: 50px;
  margin: 0;
  padding: 0;
  border: 0;
}

.el-select {
  width: 99%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
